const Koa = require('koa');
const koaStaticCache = require('koa-static-cache');
const KoaRouter = require('koa-router');
const http = require('http');
const proxy = require('koa-server-http-proxy');

const server = new Koa();

server.use(koaStaticCache({
    prefix: '/public',
    dir: './public',
    gzip: true,
    dynamic: true
}));

const router = new KoaRouter();

/**
 * 正向代理
 *  {客户端脚本（xhr）} =>  {API服务器} : 跨域
 *  {客户端脚本（xhr） => 代理 } =>  {API服务器} : 跨域
 *
 * 反向代理
 *  {客户端脚本（xhr）} =>  {代理 => API服务器} : 跨域
 */

server.use(proxy('/api', {
    target: 'http://localhost:8888',
    // 把当前请求的path转成目标服务器实际path
    pathRewrite: { '^/api': '' },
    changeOrigin: true
}));

router.get('/data', async (ctx, next) => {
    // ctx.body = [1,2,3];

    // 接收到请求以后，node.js去发送一个http请求，请求实际的资源

    let data = await request();

    ctx.body = data;

});

server.use(router.routes());

server.listen(7777);

function request() {
    return new Promise(((resolve, reject) => {
        const options = {
            protocol: 'http:',
            hostname: 'localhost',
            port: 8888,
            path: '/users',
            method: 'get',
        }
        const req = http.request(options, (res) => {
            let data = '';
            res.on('data', (chunk) => {
                data += chunk.toString();
            });
            res.on('end', () => {
                console.log('请求完成：', data);
                resolve(data);
            });
        });

        req.end('');
    }))
}
